<?php
namespace App\Listeners\System\Permission\TreeOrg;

use App\Events\System\Permission\TreeOrg\Updated;
use App\Models\Agency\Auth\Permission\Tree;
use App\Models\Agency\Auth\Permission\TreeOrg;
use App\Models\Game\Platform\Org;
use App\Services\Permission\RoleService;
use App\Services\Permission\PermissionService;

class TreeRolesRevokeOrgPermissions
{

    /**
     * 角色(授权树)递归回收授权平台
     *
     * @param Updated $event
     * @return void
     */
    public function handle(Updated $event)
    {
        if (! count($event->orgIdsDetach)) {
            return null;
        }

        // 平台ID【之前的】
        $orgIdsOld = Org::makeAllOrgs($event->orgIdsOld)->pluck('id')->all();
        // 平台ID【之后的】
        $orgIdsNew = Org::makeAllOrgs($event->orgIdsNew)->pluck('id')->all();

        // 平台ID【移除关联】
        $orgIdsDetach = array_diff($orgIdsOld, $orgIdsNew);

        if (! count($orgIdsDetach)) {
            return null;
        }

        $roleService = new RoleService();
        $permissionService = new PermissionService();

        // 所有子孙节点
        $trees = Tree::selectChildById($event->tree->id);

        // 需要回收的父级节点
        $detachParentIds = [$event->tree->id];

        // 循环子孙节点
        foreach ($trees as $tree) {
            // 判断是否回收
            if (! in_array($tree->parent_id, $detachParentIds)) {
                continue;
            }

            // 平台ID
            $orgIds = $tree->orgs->pluck('id')
                ->intersect($orgIdsDetach)
                ->all();

            // 判断是否回收
            if (! count($orgIds)) {
                continue;
            }

            // 制作平台权限
            $permissions = $permissionService->orgPermissions($orgIds);
            // 角色删除多平台权限
            $roleService->treeRoleRemovePermissions($tree->id, $permissions);

            // 标记回收节点
            array_push($detachParentIds, $tree->id);
        }

        // 回收全部关联【子孙节点】
        TreeOrg::whereIn('tree_id', $trees->pluck('id')->all())->whereIn('org_id', $orgIdsDetach)->delete();
    }
}
